package com.juzhencms.apps.busi.service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.juzhencms.apps.base.busi.mapper.AppWeixinSourceMapper.AppWeixinSourceListParam;
import com.juzhencms.apps.base.busi.service.WeixinApiService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.FileUtil;
import com.juzhencms.apps.base.common.util.HtmlUtil;
import com.juzhencms.apps.base.common.util.HttpUtil;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.busi.web.AppReplyController;

import lombok.extern.slf4j.Slf4j;


@Service("remote.appWeixinSourceService")
@Slf4j
public class AppWeixinSourceService extends CommonService{
	static final String NEWS_COLUMNS=" id,content,name,image,data_history_id,author,description "; 
	
	@Autowired
	private WeixinApiService weixinApiService;
	
	public Map getDetailById(int id) {		
		/*		String sql="SELECT * FROM "+DBTable.appWeiXinSorce+" where del_flag=0 and id=? limit 0,1";
				Map weiXinsource=this.getJdbcDao().queryRow(sql, new Object[] {id});
		*/		
		Map weiXinsource=this.getAppWeixinSourceMapper().get(id);
		return weiXinsource;
	}
    public HashMap getAppWeixinNewSource(int site_id,String newsIDStr ) {	    	
		return getAppWeixinNewSource(site_id,newsIDStr,"news");
	}
    public HashMap getAppWeixinNewSource(int site_id,String newsIDStr,String type ) {	    	
    	AppWeixinSourceListParam param = new AppWeixinSourceListParam();
    	param.setSiteId(site_id);
    	param.setNewsIDStr(newsIDStr);
    	param.setDataType(type);
    	HashMap weiXinsource=this.getAppWeixinSourceMapper().getAppWeixinSource(param);
		return weiXinsource;
	}
    public HashMap getAppWeixinImageSource(int site_id,String fileURL ) {	    	
    	AppWeixinSourceListParam param = new AppWeixinSourceListParam();
    	param.setSiteId(site_id);
    	param.setFileURL(fileURL);
    	param.setDataType("image");
    	HashMap weiXinsource=this.getAppWeixinSourceMapper().getAppWeixinSource(param);
		return weiXinsource;
	}
	
	
	public Map addWeiXinNewsSource(int siteID,List newsList) {		
		
		
		String access_token=this.weixinApiService.getAccessTokenBySiteID(siteID);
		Map result=new HashMap();
		if(StringUtil.isNullOrEmpty(access_token)){
			result.put("result", 0);
			result.put("msg", "access_token获取失败");
			return result;
		}
		String news_id=",";
		String data_history_id=",";						
		for(int i=0;i<newsList.size();i++) {
			Map row=(Map) newsList.get(i);	
			String sql="SELECT "+NEWS_COLUMNS+" FROM "+DBTable.news+" where del_flag=0 and id=?";
			Map newsInfo=this.getJdbcDao().queryRow(sql, new Object[] {row.get("id")});
			if(newsInfo!=null && newsInfo.size()>0) {
			  news_id+=newsInfo.get("id")+",";
			  data_history_id+=newsInfo.get("data_history_id")+",";
			  row.putAll(newsInfo);
			}else { 
				newsList.remove(i);
			}		
		}
		if(newsList.size()==0) {
			result.put("result", 0);
			result.put("msg", "文章信息有误请重新选择！");
			return result;
		}	
		Map weiXInSource=this.getAppWeixinNewSource(siteID,news_id);
		if(weiXInSource!=null && weiXInSource.size()>0) {			
			if(data_history_id.equals(weiXInSource.get("data_history_id")+"")) {
				weiXInSource.put("result", 1);
				return weiXInSource;
			}else { //需要更新永久素材
				
				//判断更新的是哪一条
				String data_history_id_old = weiXInSource.get("data_history_id")+"";
				String _data_history_id_old=data_history_id_old.substring(1);				
				String[] historyOldList = _data_history_id_old.split(",");				
				for(int i=0;i<newsList.size();i++) {
					Map row=(Map) newsList.get(i);
					if(!historyOldList[i].equals(row.get("data_history_id")+"")) {
						int sourceID=new Integer(weiXInSource.get("id")+"");
						this.updateWeixinNewsSource(new Integer(row.get("id")+""), weiXInSource, access_token);
					}
				}	
				weiXInSource.put("result", 1);
				return weiXInSource;
			}
		}	
		//调取微信的接口，（新增图文素材）
		ArrayList articles = new ArrayList();			
		for(int i=0;i<newsList.size();i++) {
			Map newsInfo=(Map) newsList.get(i);	
			Map articleInfo=this.makeAppWeixinNewsSource(siteID, newsInfo, access_token);
			//处理html中的数据
			articles.add(articleInfo); //
		}
		if(articles.size()>0) {
			String url=Config.getValue("weixin.apiURL")+"/material/add_news?access_token="+access_token;
			Map<String, Object> postParam=new HashMap();
			postParam.put("articles", articles);
			JSONObject jsonObj=new JSONObject(postParam);
			//log.info("上传图文素材参数--------"+jsonObj.toString());
			String postResult=HttpUtil.post(url,jsonObj.toString());
			Map resultMap=JSON.parseObject(postResult,Map.class);
			log.info("上传图文素材结果--------"+resultMap);
			if(resultMap.get("errcode")!=null) {
				result.put("result", 0);
				result.put("msg", resultMap.get("errmsg"));
				return result;
			}else {
				String media_id=resultMap.get("media_id")+"";
				//保存
				Map addInfo=new HashMap();
				addInfo.put("news_id", news_id);
				addInfo.put("data_history_id", data_history_id);
				addInfo.put("site_id", siteID);
				addInfo.put("media_id", media_id);
				addInfo.put("data_type", "news");
				addInfo.put("create_time", new Date());
				addInfo.put("forever", 1);
				addInfo.put("contents", JSON.toJSONString(articles));
				
				
				int weiXinSorceID = this.getJdbcDao().addObj(DBTable.appWeiXinSorce, addInfo);
				addInfo.remove("contents");
				addInfo.put("result", 1);
				addInfo.put("id", weiXinSorceID);
				return addInfo;
			}
		}else {
			result.put("result", 0);
			result.put("msg", "文章信息有误请重新选择！");
			return result;
		}
	}
	
	/**
	 * 为数据版本在管理公众号创建图文素材，用于微信端预览
	 * @param dataHistoryId
	 * @return
	 */
	/*public Map addWeiXinPreviewSource(int dataHistoryId) {
		String appid=Config.getValue("weixin.appId");
		String secret=Config.getValue("weixin.appSecret");
		String access_token=this.weixinApiService.getAccessToken(appid,secret);
		Map result=new HashMap();
		if(StringUtil.isNullOrEmpty(access_token)){
			result.put("result", 0);
			result.put("msg", "access_token获取失败");
			return result;
		}
		String news_id=",";
		String data_history_id=",";	
		
		Map dataHistory=this.getJdbcDao().queryRow("select * from "+DBTable.dataHistory+" where id=? ", new Object[] {dataHistoryId});
		if(dataHistory==null) {
			result.put("result", 0);
			result.put("msg", "数据不存在");
			return result;
		}

		List newsList=new ArrayList();
		
		if(dataHistory.get("data_type").toString().equals(DBTable.news)) {
			newsList.add(dataHistory.get("data_id"));
		}
		
		
		for(int i=0;i<newsList.size();i++) {
			Map row=(Map) newsList.get(i);	
			String sql="SELECT "+NEWS_COLUMNS+" FROM "+DBTable.news+" where del_flag=0 and id=?";
			Map newsInfo=this.getJdbcDao().queryRow(sql, new Object[] {row.get("id")});
			if(dataHistory!=null) {
				if(dataHistory.get("params")!=null) {
					//使用最新的版本字段替换掉当前主表字段进行显示
					Map param=JSON.parseObject(dataHistory.get("params").toString(),Map.class);
					if(param!=null) {
						for(Object key : param.keySet()) {
							if(param.get(key)!=null) {
								newsInfo.put(key, param.get(key));
							}
						}
					}
				}
			}
			if(newsInfo!=null && newsInfo.size()>0) {
			  news_id+=newsInfo.get("id")+",";
			  data_history_id+=dataHistory.get("id")+",";
			  row.putAll(newsInfo);
			}else { 
				newsList.remove(i);
			}		
		}
		if(newsList.size()==0) {
			result.put("result", 0);
			result.put("msg", "文章信息有误请重新选择！");
			return result;
		}
		Map weiXInSource=this.getAppWeixinNewSource(0,news_id,"newsPreview");
		if(weiXInSource!=null && weiXInSource.size()>0) {			
			if(data_history_id.equals(weiXInSource.get("data_history_id")+"")) {
				weiXInSource.put("result", 1);
				return weiXInSource;
			}else { //需要更新永久素材
				
				//判断更新的是哪一条
				String data_history_id_old = weiXInSource.get("data_history_id")+"";
				String _data_history_id_old=data_history_id_old.substring(1);				
				String[] historyOldList = _data_history_id_old.split(",");				
				for(int i=0;i<newsList.size();i++) {
					Map row=(Map) newsList.get(i);
					if(!historyOldList[i].equals(row.get("data_history_id")+"")) {
						int sourceID=new Integer(weiXInSource.get("id")+"");
						this.updateWeixinNewsSource(new Integer(row.get("id")+""), weiXInSource, access_token);
					}
				}	
				weiXInSource.put("result", 1);
				return weiXInSource;
			}
		}	
		//调取微信的接口，（新增图文素材）
		ArrayList articles = new ArrayList();			
		for(int i=0;i<newsList.size();i++) {
			Map newsInfo=(Map) newsList.get(i);	
			Map articleInfo=this.makeAppWeixinNewsSource(siteID, newsInfo, access_token);
			//处理html中的数据
			articles.add(articleInfo); //
		}
		if(articles.size()>0) {
			String url=Config.getValue("weixin.apiURL")+"/material/add_news?access_token="+access_token;
			Map<String, Object> postParam=new HashMap();
			postParam.put("articles", articles);
			JSONObject jsonObj=new JSONObject(postParam);
			//log.info("上传图文素材参数--------"+jsonObj.toString());
			String postResult=HttpUtil.post(url,jsonObj.toString());
			Map resultMap=JSON.parseObject(postResult,Map.class);
			log.info("上传图文素材结果--------"+resultMap);
			if(resultMap.get("errcode")!=null) {
				result.put("result", 0);
				result.put("msg", resultMap.get("errmsg"));
				return result;
			}else {
				String media_id=resultMap.get("media_id")+"";
				//保存
				Map addInfo=new HashMap();
				addInfo.put("news_id", news_id);
				addInfo.put("data_history_id", data_history_id);
				addInfo.put("site_id", siteID);
				addInfo.put("media_id", media_id);
				addInfo.put("data_type", "news");
				addInfo.put("create_time", new Date());
				addInfo.put("forever", 1);
				int weiXinSorceID = this.getJdbcDao().addObj(DBTable.appWeiXinSorce, addInfo);
				addInfo.put("result", 1);
				addInfo.put("id", weiXinSorceID);
				return addInfo;
			}
		}else {
			result.put("result", 0);
			result.put("msg", "文章信息有误请重新选择！");
			return result;
		}
	}*/
	
	
	public Map getWeinXinImageSource(int siteID,String file_url,String data_type) {
		if(StringUtil.isNullOrEmpty(data_type)) {
			data_type="image";
		}
		String sql="SELECT file_url,site_id,weixin_url,id,media_id,weixin_url FROM "+DBTable.appWeiXinSorce+" where del_flag=0 and site_id=? and file_url=? and data_type=? limit 0,1";
		Map source=this.getJdbcDao().queryRow(sql, new Object[] {siteID,file_url,data_type});
		return source;		
	}
	
	public Map getWeinXinImageSourceById(int id) {
		String sql="SELECT file_url,site_id,weixin_url,id,media_id,weixin_url FROM "+DBTable.appWeiXinSorce+" where del_flag=0 and id=? limit 0,1";
		Map source=this.getJdbcDao().queryRow(sql, new Object[] {id});
		return source;		
	}
	public Map addWeinXinImageSource(int siteID,String file_url,String access_token) {
		Map source = this.getWeinXinImageSource(siteID, file_url,null);
		if(source!=null && source.size()>0) {
			source.put("result", 1);
			return source;
		}else {		
			Map result=new HashMap();
			if(StringUtil.isNullOrEmpty(access_token)) {				
				access_token=this.weixinApiService.getAccessTokenBySiteID(siteID);
				if(StringUtil.isNullOrEmpty(access_token)){
					result.put("result", 0);
					result.put("msg", "access_token获取失败");
					return result;
			   }
			}						
			String url=Config.getValue("weixin.apiURL")+"/material/add_material?access_token="+access_token+"&type=image";
			String postResult;
			try {
				String imagePath=Config.getUploadFilePath() +"/"+file_url;
				File file = new File(imagePath);
				postResult = HttpUtil.connectHttpsByPost(url,file);
				Map resultMap=JSON.parseObject(postResult,Map.class);			
				log.info("上传封面图片数据---------resultMap==="+resultMap);
				if(resultMap.get("errcode")!=null) {
					result.put("result", 0);
					result.put("msg", resultMap.get("errmsg"));
					return result;
				}else {
					String media_id=resultMap.get("media_id")+"";
					//保存
					Map addInfo=new HashMap();
					addInfo.put("site_id", siteID);
					addInfo.put("media_id", media_id);
					addInfo.put("data_type", "image"); //（image）、
					addInfo.put("file_url", file_url);
					addInfo.put("weixin_url", resultMap.get("url"));
					addInfo.put("create_time", new Date());
					addInfo.put("forever", 1);
					int sourceID = this.getJdbcDao().addObj(DBTable.appWeiXinSorce, addInfo);
					addInfo.put("id", sourceID);
					addInfo.put("result", 1);
					return addInfo;
				}
			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result.put("result", 0);
				result.put("msg",e.getMessage());
				return result;
			}
		}
	}
	
	
	
	/*上传图文消息内的图片获取URL，本接口所上传的图片不占用公众号的素材库中图片数量的100000个的限制。图片仅支持jpg/png格式，大小必须在1MB以下。
	 * siteID 微信公众号 
	   * 公众号的access_token
	 * file_url_net 图片访问url
	 * 
	 * 
	 * */
	public String  uploadImageForNewsByNetUrl(int siteID,String file_url_net,String access_token) {
		Map source = this.getWeinXinImageSource(siteID, file_url_net,"image_news");
		//查询之前是否上传过，避免重复上传
		if(source!=null && source.size()>0) {
			source.put("result", 1);
			if(StringUtil.isNotNullOrEmpty(source.get("weixin_url"))) {
				return source.get("weixin_url")+"";
			}else {
				source.put("del_flag", 1); //不对的就删除掉
				this.getJdbcDao().updateObj(DBTable.appWeiXinSorce, source, "id");
			}
		}	
		Map result=new HashMap();
		String url=Config.getValue("weixin.apiURL")+"/media/uploadimg?access_token="+access_token+"&type=image";
		//Map<String, Object> postParam=new HashMap();
		//postParam.put("image",file_url_net);	
		String postResult;
		try {
			
			//判断是否是本地素材
			boolean isLocalFile=false;
			File file=null;
			if(file_url_net.indexOf(Config.getUploadUrlPath())==0){
				isLocalFile=true;
				file=new File(file_url_net.replace(Config.getUploadUrlPath(), Config.getUploadFilePath()));
			}else {
				file=FileUtil.getTempFile(file_url_net);
			}
			
			
			postResult=HttpUtil.connectHttpsByPost(url,file);
			//log.info("uploadimg result:"+postResult);
			Map resultMap=JSON.parseObject(postResult,Map.class);			
			if(StringUtil.isNotNullOrEmpty(resultMap.get("url"))) {
				Map addInfo=new HashMap();
				addInfo.put("site_id", siteID);
				//addInfo.put("media_id", media_id);
				addInfo.put("data_type", "image_news"); //（image）、
				addInfo.put("file_url", file_url_net);
				addInfo.put("weixin_url", resultMap.get("url"));
				addInfo.put("create_time", new Date());
				int sourceID = this.getJdbcDao().addObj(DBTable.appWeiXinSorce, addInfo);
				return resultMap.get("url")+"";
			}
			if(file.exists() && !isLocalFile) {
				file.delete();
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public String uploadVideoForNewsByNetUrl(int siteID,String file_url_net,String access_token) {
		Map source = this.getWeinXinImageSource(siteID, file_url_net,"video_news");
		//查询之前是否上传过，避免重复上传
		if(source!=null && source.size()>0) {
			source.put("result", 1);
			if(StringUtil.isNotNullOrEmpty(source.get("media_id"))) {
				return source.get("media_id")+"";
			}else {
				source.put("del_flag", 1); //不对的就删除掉
				this.getJdbcDao().updateObj(DBTable.appWeiXinSorce, source, "id");
			}
		}	
		Map result=new HashMap();
		String url=Config.getValue("weixin.apiURL")+"/material/add_material?access_token="+access_token+"&type=video";
		//String url=Config.getValue("weixin.apiURL")+"/media/uploadimg?access_token="+access_token+"&type=video";
		//Map<String, Object> postParam=new HashMap();
		//postParam.put("image",file_url_net);	
		String postResult;
		try {
			
			//判断是否是本地素材
			boolean isLocalFile=false;
			File file=null;
			if(file_url_net.indexOf(Config.getUploadUrlPath())==0){
				isLocalFile=true;
				file=new File(file_url_net.replace(Config.getUploadUrlPath(), Config.getUploadFilePath()));
				//log.info(file.getName());
				//log.info(file.getAbsolutePath());
				//log.info("size:"+file.length());
			}else {
				file=FileUtil.getTempFile(file_url_net);
				//log.info(file.getName());
				//log.info(file.getAbsolutePath());
				//log.info("size:"+file.length());
			}
			//log.info(url);
			
			Date timenow=new Date();
			String title="视频"+timenow.getTime();
			
			postResult=HttpUtil.connectHttpsByPost(url,file,title,title);
			log.info("uploadvideo result:"+postResult);
			Map resultMap=JSON.parseObject(postResult,Map.class);			
			if(StringUtil.isNotNullOrEmpty(resultMap.get("media_id"))) {
				Map addInfo=new HashMap();
				addInfo.put("site_id", siteID);
				addInfo.put("media_id", resultMap.get("media_id"));
				addInfo.put("data_type", "video_news"); //（image）、
				addInfo.put("file_url", file_url_net);
				//addInfo.put("weixin_url", resultMap.get("url"));
				addInfo.put("create_time", new Date());
				int sourceID = this.getJdbcDao().addObj(DBTable.appWeiXinSorce, addInfo);
				return resultMap.get("media_id")+"";
			}
			if(file.exists() && !isLocalFile) {
				file.delete();
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	
	public ArrayList getWeiXinSourceNewsList(int id) {
		Map weiXinSource=this.getDetailById(id);
		ArrayList newsList = new ArrayList();
		if(weiXinSource!=null && weiXinSource.size()>0) {
			String newsStr= weiXinSource.get("news_id")+"";
			newsStr=newsStr.substring(1,newsStr.lastIndexOf(","));
			String[] newsIDList = newsStr.split(",");
			for(int i=0;i<newsIDList.length;i++) {
				String newsID = newsIDList[i];
				String sql="SELECT id,name,hits,publish,recommend,position,create_user,create_time,image FROM "+DBTable.news+" where id=? and del_flag=0";
				Map newsInfo=this.getJdbcDao().queryRow(sql, new Object[] {newsID});
				if(newsInfo!=null && newsInfo.size()>0) {
					if(StringUtil.isNotNullOrEmpty(newsInfo.get("image"))) {
						newsInfo.put("_image",Config.getUploadUrlPath()+"/"+newsInfo.get("image"));
					}else newsInfo.put("_image",Config.getUploadUrlPath()+"/nophoto.jpg");
					
					newsList.add(newsInfo);
				}
			}
		}	
		return newsList;
	}
	public Map makeAppWeixinNewsSource(int siteID,Map newsInfo,String access_token) {
		Map articleInfo=new HashMap();
		articleInfo.put("title", newsInfo.get("name")+"");
		Map tempParam2=new HashMap();
		tempParam2.put("file_url",newsInfo.get("image"));
		Map weiXInImageSource=this.getAppWeixinImageSource(siteID, newsInfo.get("image")+"");
		
		//log.info("weiXInImageSource1:"+JSON.toJSONString(weiXInImageSource));
		
		
		
		String thumb_media_id="";
		if(weiXInImageSource!=null && weiXInImageSource.size()>0) {
			thumb_media_id=weiXInImageSource.get("media_id")+"";
		}else {		
			//增加
			weiXInImageSource= this.addWeinXinImageSource(siteID,newsInfo.get("image")+"",access_token);
			thumb_media_id=weiXInImageSource.get("media_id")+"";
		}
		
		//log.info("weiXInImageSource2:"+JSON.toJSONString(weiXInImageSource));
		
		
		articleInfo.put("thumb_media_id", thumb_media_id);
		if(StringUtil.isNotNullOrEmpty( newsInfo.get("author"))) {
			articleInfo.put("author", newsInfo.get("author")+"");
		}else {
			articleInfo.put("author", " ");
		}
		if(StringUtil.isNotNullOrEmpty( newsInfo.get("description"))) {
			articleInfo.put("digest",  newsInfo.get("description")+"");
		}else {
			articleInfo.put("digest"," ");
		}
		articleInfo.put("show_cover_pic", 0); //是否显示封面，0为false，即不显示，1为true，即显示
		
		
		
		if(newsInfo.get("content")!=null) {
			String html = newsInfo.get("content")+"";
			//log.info("html:"+html);
			
			//将非微信域名下的图片上传至微信图片库并转换为微信域名
			Set<String> imageList = HtmlUtil.getImgStr( newsInfo.get("content")+"");
			if (!imageList.isEmpty()) {
				for (String str : imageList) { 
					//如果图片url是微信图片库，则忽略这一步，以提升同步速度
					if(str.indexOf("//mmbiz.qlogo.cn/")>0 || str.indexOf("//mmbiz.qpic.cn/")>0) {
						continue;
					}
					
					//处理文章里的图片，文件
					String weiXinURL=this.uploadImageForNewsByNetUrl(siteID, str, access_token);
				    if(StringUtil.isNotNullOrEmpty(weiXinURL)) {
				    	html = html.replace(str, weiXinURL);
				    }					
				}  
			}
			//log.info("html_2:"+html);
			
			//如果存在小程序链接的话，小程序链接属性中将href属性设置为空字符串
			List miniprogramLinkList=new ArrayList();
			Pattern p=Pattern.compile("<a\\s+[^>]*data-miniprogram-appid[^>]*>",Pattern.CASE_INSENSITIVE);
			Matcher m=p.matcher(html);
			while(m.find()){//此方式表示是否包含
				miniprogramLinkList.add(m.group());
			}
			Pattern p2=Pattern.compile("href\\s*=\\s*(\"|')?([^\"'\\s]+)(\"|')?",Pattern.CASE_INSENSITIVE);
			for(int i=0;i<miniprogramLinkList.size();i++) {
				String tmpLink=miniprogramLinkList.get(i).toString();
				Matcher m2=p2.matcher(tmpLink);
				if(m2.find()){
					String newLink=tmpLink.replace(m2.group(), "href=\"\"");
					html = html.replace(tmpLink, newLink);
				}
			}
			
			//替换视频代码
			List videoList=new ArrayList();
			//正则表达式获取视频代码
			Pattern videoCodePattern=Pattern.compile("<video\\s+.+?</video>",Pattern.CASE_INSENSITIVE);
			Matcher videCodeMatcher=videoCodePattern.matcher(html);
			while(videCodeMatcher.find()){//此方式表示是否包含
				videoList.add(videCodeMatcher.group());
			}
			
			//log.info("videoList:"+JSON.toJSONString(videoList));
			
			for(int i=0;i<videoList.size();i++) {
				String tmpVideo=videoList.get(i).toString();
				String newVideoCode="";
				//从视频代码中获取视频url
				Pattern videoUrlPattern=Pattern.compile("src\\s*=\\s*(\"|')?([^\"'\\s]+)(\"|')?",Pattern.CASE_INSENSITIVE);
				Matcher videUrlMatcher=videoUrlPattern.matcher(tmpVideo);
				if(videUrlMatcher.find()){//此方式表示是否包含
					String videoUrl=videUrlMatcher.group(2);
					
					//log.info("videoUrl "+i+":"+videoUrl);
					
					if(videoUrl!=null && !videoUrl.equals("")) {
						String weixinVideoMediaId=this.uploadVideoForNewsByNetUrl(siteID, videoUrl, access_token);
					    if(StringUtil.isNotNullOrEmpty(weixinVideoMediaId)) {
					    	//通过接口获取微信视频vid
					    	try {
					    		String vid=getVideoVid(weixinVideoMediaId,access_token);
					    		
					    		newVideoCode="<iframe class='video_iframe rich_pages' data-vidtype='2' data-mpvid='"+vid+"' allowfullscreen='' frameborder='0' style='z-index:1;height:320px;' data-w='1280' data-src='https://mp.weixin.qq.com/mp/readtemplate?t=pages/video_player_tmpl&action=mpvideo&auto=0&vid="+vid+"'></iframe>";
					    		
					    	}catch(Exception e) {
					    		log.error(e.getMessage(),e);
					    	}
					    	
					    	
					    	
					    	//拼接新的视频代码
					    	//newVideoCode="<iframe class=\"video_iframe wx_video_iframe rich_pages\" data-vidtype=\"2\" data-mpvid=\""+weixinVideoMediaId+"\" allowfullscreen=\"\" frameborder=\"0\" style=\"position:relative; z-index:1;\" height=\"434\" width=\"578\" src=\"/cgi-bin/readtemplate?t=tmpl/video_tmpl&amp;vid="+weixinVideoMediaId+"\" data-w=\"1280\"></iframe>";
					    	//newVideoCode="<iframe frameborder=\"0\" width=\"100%\" height=\"200px\" src=\"https://v.qq.com/iframe/player.html?vid="+weixinVideoMediaId+"\" allowfullscreen=\"true\"></iframe>";
					    	//<iframe frameborder="0" width="100%" height="200px" src="https://v.qq.com/iframe/player.html?vid=m3080z2tety" allowfullscreen="true"></iframe>
					    }
					}	
				}
			    //使用微信素材代码替换视频代码
				html = html.replace(tmpVideo, newVideoCode);
			}
			log.info("mdeia html:"+html);
			articleInfo.put("content", html); 
		}else {
			articleInfo.put("content", " ");
		}
		
		///设置文章的原文地址//app.domain
		String content_source_url=Config.getValue("app.domain")+"newsInfo_"+newsInfo.get("id");
		articleInfo.put("content_source_url", content_source_url); 
		return articleInfo;
	}
	
	//更新
	public void updateWeixinNewsSource(int newsID,Map weiXinsource,String access_token) {
		if(weiXinsource!=null && weiXinsource.size()>0) {
			int sourceID =new Integer(weiXinsource.get("id")+"");
			int siteID=new Integer(weiXinsource.get("site_id")+"");
			if(StringUtil.isNullOrEmpty(access_token)) {				
				access_token=this.weixinApiService.getAccessTokenBySiteID(siteID);
				if(StringUtil.isNullOrEmpty(access_token)){
					this.getAppWeixinSourceMapper().updateDataHistoryId(sourceID, null,"素材更新失败：access_token获取失败");	
					return ;
				}
			}	
			if(StringUtil.isNotNullOrEmpty(weiXinsource.get("news_id"))) {
				String newsIDStr=weiXinsource.get("news_id")+"";
				String data_history_id=weiXinsource.get("data_history_id")+"";
				data_history_id=data_history_id.substring(1,data_history_id.lastIndexOf(","));
				String[] historyList = data_history_id.split(",");
				newsIDStr=newsIDStr.substring(1,newsIDStr.lastIndexOf(","));
				String[] newsIDList = newsIDStr.split(",");
				for(int i=0;i<newsIDList.length;i++) {
					int  id =new Integer(newsIDList[i]);					
					if(id==newsID) {
						//查找新闻的信息
						Map newsInfo = this.getJdbcDao().queryRow("select "+NEWS_COLUMNS+" from "+DBTable.news+" where id=?", new Object[] {newsID});
						Map articleInfo=this.makeAppWeixinNewsSource(siteID, newsInfo, access_token);
						historyList[i]=newsInfo.get("data_history_id")+"";
						String url=Config.getValue("weixin.apiURL")+"/material/update_news?access_token="+access_token;
						Map<String, Object> postParam=new HashMap();
						postParam.put("media_id", weiXinsource.get("media_id"));
						postParam.put("index", i);						
						postParam.put("articles", articleInfo);
						JSONObject jsonObj=new JSONObject(postParam);	
						log.info(jsonObj.toString()+"-----updateWeixinNewsSource----requestData");
						String postResult=HttpUtil.post(url,jsonObj.toString());
						Map resultMap=JSON.parseObject(postResult,Map.class);
						log.info(resultMap+"-----updateWeixinNewsSource----resultMap");
					    if(StringUtil.isNullOrEmpty(resultMap.get("errcode")) || "0".equals(resultMap.get("errcode")+"")) { //成功						    
					    	String historyIDStr="";
					    	for(int n=0;n<historyList.length;n++) {
					    		if(n==0) {
					    			historyIDStr+=","+historyList[n]+",";
					    		}else historyIDStr+=historyList[n]+",";
					    	}
					    	this.getAppWeixinSourceMapper().updateDataHistoryId(sourceID, historyIDStr,resultMap.get("errmsg")+"");					    	
					    }else { //记录更新失败				    	
					    	this.getAppWeixinSourceMapper().updateDataHistoryId(sourceID, null,resultMap.get("errmsg")+"");		
					    }						
					}
				}
			}
		}
	}
	public void deleteWeixinNewsSource(Map weiXinsource) {
		int siteID=new Integer(weiXinsource.get("site_id")+"");		
		String access_token=this.weixinApiService.getAccessTokenBySiteID(siteID);
		Map result=new HashMap();
		if(StringUtil.isNullOrEmpty(access_token)){
			this.getAppWeixinSourceMapper().updateDataHistoryId(new Integer(weiXinsource.get("id")+""), null,"删除失败：access_token获取失败");	
		}else {		
			Map<String, Object> postParam=new HashMap();
			String url=Config.getValue("weixin.apiURL")+"/material/del_material?access_token="+access_token;
			postParam.put("media_id", weiXinsource.get("media_id"));
			JSONObject jsonObj=new JSONObject(postParam);		
			String postResult=HttpUtil.post(url,jsonObj.toString());
			Map resultMap=JSON.parseObject(postResult,Map.class);
			if(StringUtil.isNullOrEmpty(resultMap.get("errcode")) || "0".equals(resultMap.get("errcode")+"")) { //成功	    	
		    	this.getAppWeixinSourceMapper().deleteData(new Integer(weiXinsource.get("id")+""));		
		    	
		    	
		    	
		    }else { //记录更新失败				    	
		    	this.getAppWeixinSourceMapper().updateDataHistoryId(new Integer(weiXinsource.get("id")+""), null,"删除失败："+resultMap.get("errmsg"));		
		    }
		}
	}
	
	public String getVideoVid(String mediaId,String accessToken) throws ParseException, IOException {
		
		String url=Config.getValue("weixin.apiURL")+"/material/get_material?access_token="+accessToken;
		
	    CloseableHttpClient httpclient = HttpClients.createDefault();
	    Map param=new HashMap();
	    param.put("media_id", mediaId);
	    
	    // 创建httppost
	    
	    //log.info(url);
	    
	    HttpPost httppost = new HttpPost(url);
	    httppost.addHeader("Content-type", "application/json; charset=utf-8");
	    httppost.setHeader("Accept", "application/json");
	    
	    
	    StringEntity s = new StringEntity(JSON.toJSONString(param),Charset.forName("UTF-8"));  //对参数进行编码，防止中文乱码
    	s.setContentEncoding("UTF-8");
    	httppost.setEntity(s);
        CloseableHttpResponse response = httpclient.execute(httppost);  
        try {
        	//获取相应实体
            HttpEntity entity = response.getEntity();  
            if (entity != null) {  
            	String info=EntityUtils.toString(entity, "UTF-8");
            	log.info(info);
            	Map result=JSON.parseObject(info,Map.class);
            	if(result!=null && result.get("vid")!=null) {
            		return result.get("vid").toString();
            	}
            }  
            
        } finally {  
            response.close();  
        } 
        httpclient.close();
        return null;
	}
	
}
